//
//  TSCVCGuideMain.m
//  Tsc_IOS
//
//  Created by Rio on 15-5-12.
//  Copyright (c) 2015年 idream. All rights reserved.
//

#import "TSCVCGuideMain.h"
#import "TSCVCLogin.h"
#import "TSCVCStory.h"
#import "TSCVCGuideSpace.h"
#import "TSCSDK.h"
#import "TSCVCCustomerSpace.h"
#import "TSCVCGuideSpace.h"
#import "TSCVCAbout.h"
#import "TSCVCSetting.h"
#import "TSCVCFeedback.h"
#import "TSCVCGuideBizList.h"
#import "TSCMySidebar.h"


@implementation TSCVCGuideMain {
    BOOL _iIsPopStory; // 是否弹出“我们的故事”
    
    TSCMyPopupMenu * _popMenu;
    NSArray * _ivIntroPicArr;
}

#pragma mark 校验并获取输入

- (void) getVCInput:(NSNotificationCenter *)notification {
    [super getVCInput:notification];
    
    _iIsPopStory = [[_inputDic objectForKey:AEKI_IS_POP_STORY] boolValue];
}

+ (id)vcGuideMainWithStoryboard {
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    return [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_GUIDE_MAIN];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 判断是否需要开启我们的故事，如是，则弹出“我们的故事”
    if (_iIsPopStory) {
        [TSCMyUIUtil popVCStoryWithVC:self];
    }
    
    // 如果第一次打开APP，则显示帮助图片
    [self displayIntroPic];
    
    // 先构造popupMenu，再构造naviBar
    [self constructPopupMenuAndNaviBar];
    
    // 注册观察者——当APP_DB中有新增的未处理消息时
    //    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshUnreadMsgNum) name:NOTIFICATION_NAME_UNREAD_MSG_PREFIX object:nil]; // 注：IOS中，不能通过prefix进行消息的分发
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshUnreadMsgNum) name:NOTIFICATION_NAME_UNREAD_MSG_COME object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshUnreadMsgNum) name:NOTIFICATION_NAME_UNREAD_MSG_DELETED object:nil];
    
    // 刷新未读消息数量
    [self refreshUnreadMsgNum];
    
    // 异步加载界面信息
    [self getSerMainInfo_P1];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark 私有方法


- (void) constructPopupMenuAndNaviBar {
    
    // 获得SP
    NSInteger userId = [[_ud objectForKey:UD_USER_ID] integerValue];
    NSString * userName = [_ud objectForKey:UD_USER_NAME];
    NSInteger userRole = [[_ud objectForKey:UD_USER_ROLE] integerValue];
    NSInteger isManager = [[_ud objectForKey:UD_GUIDE_IS_MANAGER] integerValue];
    
    // 创建icon、text、onClick数组
    NSMutableArray * rowIconArray = [NSMutableArray array];
    NSMutableArray * rowTextArray = [NSMutableArray array];
    NSMutableArray * rowOnClickListenerArray = [NSMutableArray array];
    // 1
    [rowIconArray addObject:@"ic_user_96x96.png"]; // 先使用默认头像
    [rowTextArray addObject:userName];
    [rowOnClickListenerArray addObject:^(NSIndexPath * indexPath) {
        // 顾客
        if (userRole == DB_USER_ROLE_CUSTOMER) {
            TSCVCCustomerSpace * vc = [TSCVCCustomerSpace vcCustomerSpaceWithStoryboard];
            [self.navigationController pushViewController:vc animated:YES];
            
            NSDictionary * inputDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:userId] forKey:AEKI_CUSTOMER_ID];
            [[NSNotificationCenter defaultCenter]addObserver:vc selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_CUSTOMER_SPACE object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_CUSTOMER_SPACE object:inputDic];
        }
        // 导购
        else {
            TSCVCGuideSpace * vc = [TSCVCGuideSpace vcGuideSpaceWithStoryboard];
            [self.navigationController pushViewController:vc animated:YES];
            
            NSDictionary * inputDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:userId] forKey:AEKI_GUIDE_ID];
            [[NSNotificationCenter defaultCenter]addObserver:vc selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_GUIDE_SPACE object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_GUIDE_SPACE object:inputDic];
        }
        
        // 关闭dialog
        [_popMenu dismiss];
    }];
    // 2
    // 注：只有当用户身份为导购，且为（某店铺的）店长时才添加
    if (userRole == DB_USER_ROLE_GUIDE && isManager == DB_YES) {
        [rowIconArray addObject:@"ic_approve_96x96.png"];
        [rowTextArray addObject:@"审批店员"];
        [rowOnClickListenerArray addObject:^(NSIndexPath * indexPath) {
            NSLog(@"TODO goto审批店员...");
        }];
        
        // 关闭dialog
        [_popMenu dismiss];
    }
    // 3
    [rowIconArray addObject:@"ic_help_96x96.png"];
    [rowTextArray addObject:@"帮助"];
    [rowOnClickListenerArray addObject:^(NSIndexPath * indexPath) {
        TSCVCAbout * vc = [TSCVCAbout vcAboutWithStoryboard];
        [self.navigationController pushViewController:vc animated:YES];
        
        // 关闭dialog
        [_popMenu dismiss];
    }];
    // 4
    [rowIconArray addObject:@"ic_gear_96x96.png"];
    [rowTextArray addObject:@"设置"];
    [rowOnClickListenerArray addObject:^(NSIndexPath * indexPath) {
        TSCVCSetting * vc = [TSCVCSetting vcSettingWithStoryboard];
        [self.navigationController pushViewController:vc animated:YES];
        
        // 关闭dialog
        [_popMenu dismiss];
    }];
    // 5
    [rowIconArray addObject:@"ic_letter_96x96.png"];
    [rowTextArray addObject:@"反馈"];
    [rowOnClickListenerArray addObject:^(NSIndexPath * indexPath) {
        TSCVCFeedback * vc = [TSCVCFeedback vcFeedbackWithStoryboard];
        [self.navigationController pushViewController:vc animated:YES];
        
        // 关闭dialog
        [_popMenu dismiss];
    }];
    // 6 TODO 测试退出
    [rowIconArray addObject:@"ic_app_logo_96x96.png"];
    [rowTextArray addObject:@"退出"];
    [rowOnClickListenerArray addObject:[^(NSIndexPath * indexPath) {
        [TSCMyUtil logoutAllWithUserDefaults:_ud];
        
        // 由系统控制后续界面该如何跳转，并关闭当前界面
        TSCVCLogin *vcLogin = [TSCVCLogin vcLoginWithStoryboard];
        [[self navigationController] pushViewController:vcLogin animated:YES];
        [TSCMyUIUtil removeVCItselfAndAllPreviousVC:self];
        
        // 关闭dialog
        [_popMenu dismiss];
    } copy]];
    
    
    // 创建右上角菜单
    _popMenu = [[TSCMyPopupMenu alloc]init];
    _popMenu.rowIconArray = rowIconArray;
    _popMenu.rowTextArray = rowTextArray;
    _popMenu.rowOnClickListenerArray = rowOnClickListenerArray;
    
    // 设置自定义导航栏
    _nbc = [[TSCMyNaviBarCreator alloc]initAndCreateWithViewController:self hasGoBackButton:NO goBackVC:nil hasAppLogo:YES titleResourceKey:@"app_name" iconResourceNameArray:[NSArray arrayWithObject:@"ic_settings_96x96.png"] iconClickedListenerArray:
            [NSArray arrayWithObject:
             // 注册事件——打开设置菜单
             ^(UIButton * btn){
                 if (_popMenu.isShowing) {
                     [_popMenu dismiss];
                 } else {
                     [_popMenu show];
                 }
             }]
            ];
    
    // 后续读取APP_DB、sd_webimage等网络操作，放到异步线程中进行，不影响UI线程正常显示
    
    // 从APP_DB中读取user_pic_url
    // 注：无论是直接登录、还是顾客完成注册（包括注册2）之后，都会在APP_DB保存登录用户的信息，所以肯定可以取到
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        TSCJsonUser * jsonUser = [TSCMyDBUtil getRUserWithUserId_1:[[_ud objectForKey:UD_USER_ID] integerValue]];
        UIImageView * ivTemp = [[UIImageView alloc]init];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [ivTemp sd_setImageWithURL:[NSURL URLWithString:jsonUser.picUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                // 根据pic_url获得对应的用户头像UIImage
                UIImage * imgTemp = nil;
                if(error) { // 内存缓存、本地文件、网络上均没有图片时，error不为nil
                    NSLog(@"[E]%s: 导购首界面，通过pic_url获得当前登录用户头像图片错误！错误信息：%@", __FUNCTION__, error);
                } else {
                    imgTemp = ivTemp.image;
                }
                
                if (imgTemp) {
                    [rowIconArray setObject:imgTemp atIndexedSubscript:0]; // 如果有用户头像就使用之
                    
                    // 重新显示
                    [_popMenu refresh];
                }
            }];
        });
    });
}

- (void) displayIntroPic {
    
    // 如果第一次打开APP，则显示帮助图片
    // 注：当界面显示时才加载，避免同时显示帮助图片和我们的故事图片，导致APP因内存溢出而崩溃
    if ([_ud boolForKey:UD_HAS_GUIDE_OPENED_APP_BEFORE] == NO) {
        // 更新sp
        [_ud setBool:YES forKey:UD_HAS_GUIDE_OPENED_APP_BEFORE];
        [_ud synchronize];
        
        // 定义所有帮助图片数组和下标
        _ivIntroPicArr = [NSArray arrayWithObjects:
                          [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"help_guide_1_576x908.png"]],
                          [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"help_guide_2_576x908.png"]],
                          [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"help_guide_3_576x908.png"]],
                          [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"help_guide_4_576x908.png"]],
                          nil];
        
        // 设置iv属性
        for (NSInteger i = 0, max = [_ivIntroPicArr count]; i < max; i++) {
            UIImageView * iv = _ivIntroPicArr[i];
            // 隐藏
            iv.hidden = YES;
            // 保存tag
            iv.tag = i;
            // 添加到界面
            [self.view addSubview:iv];
            // 约束（全屏）
            iv.translatesAutoresizingMaskIntoConstraints = NO;
            [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[iv]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(iv)]];
            [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[iv]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(iv)]];
            // 注册事件——隐藏当前图片，并打开下一张图片
            iv.userInteractionEnabled = YES;
            [iv addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ivIntroClicked:)]];
            
            // 先显示第一张图片
            if (i == 0) {
                iv.hidden = NO;
            }
        }
    }
    
}

- (void) refreshUnreadMsgNum {
    
    // 从APP_DB中读取未处理消息数量，并进行显示
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSInteger userId = [[_ud objectForKey:UD_USER_ID] integerValue];
        NSInteger unreadMsgNum = [TSCMyDBUtil getUnreadMsgNumWithUserId_1:userId types:@"" isReaded:DB_ANY];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (unreadMsgNum <= 0) {
                _lbUnreadMsgNum.hidden = YES;
                _ivUnreadMsgNum.hidden = YES;
            } else {
                _lbUnreadMsgNum.text = [NSString stringWithFormat:@"%li", unreadMsgNum];
                
                _lbUnreadMsgNum.hidden = NO;
                _ivUnreadMsgNum.hidden = NO;
            }
        });
    });
    
}

- (void) getSerMainInfo_P1 {
    
    // 先检查网络情况，若不可用，直接返回
    if ([TSCMyNetworkUtil checkNetwork] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_network_unavailable"];
        return;
    }
    
    // 拼装请求
    NSMutableDictionary * reqDic = [[NSMutableDictionary alloc] init];
    [reqDic setObject:[_ud objectForKey:UD_USER_ID] forKey:@"user_id"];
    [reqDic setObject:[_ud objectForKey:UD_LOGIN_KEY] forKey:@"login_key"];
    
    // 发送请求
    [TSCMyHttpUtil postWithUrl:URL_GUIDE_GET_MAIN_INFO dictionary:reqDic completionHandler:^(ServerRespType serverRespType, NSString * respString,  NSDictionary *respDictionary, NSInteger code, NSString *msg, NSDictionary *contentDictionary) {
        // 服务器返回错误处理
        switch (serverRespType) {
            case ServerRespTypeSuccess:
                break;
            case ServerRespTypeErrNil:
            case ServerRespTypeErrJson: {
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_web_server_unavailable"];
                return;
            }
            case ServerRespTypeErrCode:{
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithString:msg];
                return;
            }
            default: {
                [self dissmisDialog];
                [TSCMyUIUtil popErrWithResourceKey:@"err_system"];
                return;
            }
        }
        
        // 解析销售达人列表
        NSArray * guideStartArr = [contentDictionary objectForKey:@"guide_star_list"];
        NSMutableArray * jsonSellStarArr = [NSMutableArray array];
        for (NSDictionary * dic in guideStartArr) {
            TSCJsonUser * jsonUser = [[TSCJsonUser alloc]init];
            jsonUser.Id = [[dic objectForKey:@"id"]integerValue];
            jsonUser.name = [dic objectForKey:@"name"];
            jsonUser.picUrl = [dic objectForKey:@"pic_url"];
            
            // 注：按Server返回的顺序依次添加
            [jsonSellStarArr addObject:jsonUser];
        }
        
        
        // 继续后续处理...
        [self getSerMainInfo_P2:jsonSellStarArr];
    }];
    
}

- (void) getSerMainInfo_P2:(NSArray *)jsonSellStartArr {
    
    NSInteger startCnt = [jsonSellStartArr count];
    if (startCnt == 0) {
        return;
    }
    
    // 创建并添加N个空的“销售达人”iv
    
    // 1 创建LinearLayout
    TSCLinearLayout * ll = [[TSCLinearLayout alloc]init];
    ll.orientation = LINEAR_LAYOUT_ORIENTATION_HORIZONTAL;
    ll.distribution = LINEAR_LAYOUT_DISTRIBUTION_FILL_EQUALLY;
    
    [self.view addSubview:ll];
    
    ll.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint constraintWithItem:ll attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_lbSellStars attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f].active = YES; // 宽度，同标题
    [NSLayoutConstraint constraintWithItem:ll attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:_btnBizComing attribute:NSLayoutAttributeHeight multiplier:1.0f constant:0.0f].active = YES; // 高度，同“生意来啦”按钮，决定了“销售达人”头像的宽度、高度
    [NSLayoutConstraint constraintWithItem:ll attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:_lbSellStars attribute:NSLayoutAttributeLeft multiplier:1.0f constant:0.0f].active = YES; // left，与标题对其
    [NSLayoutConstraint constraintWithItem:ll attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_lbSellStars attribute:NSLayoutAttributeBottom multiplier:1.0f constant:0.0f].active = YES; // top，与标题底部对其
    
    // 2 创建每一个头像
    CGFloat startImgWidth = _lbSellStars.frame.size.width; // 注：IOS中，与标题同宽（此时应该可以获得标题的宽度）
    startImgWidth = startImgWidth / startCnt;
    
    for (NSInteger i = 0; i < CONFIG_MAX_BUY_STAR_NUM && i < startCnt; i++) {
        
        TSCJsonUser * jsonUser = jsonSellStartArr[i];
        
        UIImageView * iv = [[UIImageView alloc]init];
        iv.contentMode = UIViewContentModeScaleAspectFit; // 注：需设置contentMode
        iv.tag = jsonUser.Id; // 保存userId
        [TSCMyUIUtil setUserPicIvWithUserPicUrl:jsonUser.picUrl imageView:iv isUseDefaultPic:YES onSuccess:^(){
            // 注：需要在设置iv.image成功后，再设置圆形，否则iv.image将为nil
            [TSCMyUIUtil setUIImageViewRounded:iv];
        } onFailure:nil];
        [ll addSubview:iv];
        
        // 注册事件——点击
        iv.userInteractionEnabled = YES;
        [iv addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ivSellStartClicked:)]];
        
    }
}

#pragma mark 事件响应

- (void) ivSellStartClicked:(UITapGestureRecognizer *)recognizer {
    
    TSCVCGuideSpace * vc = [TSCVCGuideSpace vcGuideSpaceWithStoryboard];
    [self.navigationController pushViewController:vc animated:YES];
    
    NSInteger userId = recognizer.view.tag;
    NSDictionary * inputDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:userId] forKey:AEKI_GUIDE_ID];
    [[NSNotificationCenter defaultCenter]addObserver:vc selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_GUIDE_SPACE object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_GUIDE_SPACE object:inputDic];
    
}

- (void) ivIntroClicked:(UITapGestureRecognizer *)recognizer {
    
    // 隐藏并移除自己
    UIImageView * ivCurrent = (UIImageView *)recognizer.view;
    ivCurrent.hidden = YES;
    [ivCurrent removeFromSuperview];
    
    // 显示下一个
    NSInteger ivIndexCurrent = ivCurrent.tag;
    if (ivIndexCurrent <= [_ivIntroPicArr count] - 2) { // 注：这里要-2，因为当前图片最大只能为倒数第二张图片，而不能是倒数第一张
        UIImageView * ivNext = _ivIntroPicArr[ivIndexCurrent + 1];
        ivNext.hidden = NO;
    }
    
}

- (IBAction)btnBizComeClicked:(id)sender {
    TSCVCGuideBizList * vc = [TSCVCGuideBizList vcGuideBizListWithStoryboard];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)btnLimitSellListClicked:(id)sender {
}

- (IBAction)btnMyReplyListClicked:(id)sender {
}

- (IBAction)btnGossipClicked:(id)sender {
}


- (void)dealloc {
    NSLog(@"TODO dealloc %@", self);
}

@end
